/**
 * JAVACC DEMO 1.0
 */
package com.apache.plateform.interceptor;

import com.apache.api.vo.ParamsVo;
import com.apache.tools.DateUtils;
import com.apache.tools.DateUtils.FmtStr;
import com.apache.tools.StrUtil;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
 * description:  产品统一系统日志处理
 *
 * @author dyhou 创建时间：2016-7-9
 */
public class LogInterceptor implements MethodBeforeAdvice, AfterReturningAdvice {//

    private Logger log = Logger.getLogger(getClass());

    @SuppressWarnings("rawtypes")
    private void before2(String methodName, Object[] objs, String className) {
        ParamsVo arguments = (ParamsVo) objs[0];
        StringBuffer sb = new StringBuffer("请求:" + className + "类中" + methodName + "方法");
        sb.append(";请求参数: ");
        if (!StrUtil.isEmpty(arguments.getObj())) {
            sb.append("obj:[" + arguments.getObj() + "]");
        }
        if (!StrUtil.isEmpty(arguments.getParams())) {
            sb.append("params:[" + arguments.getParams() + "]");
        }
        if (StrUtil.isNotNull(arguments.getKey())) {
            sb.append("key:[" + arguments.getKey() + "]");
        }
        if (StrUtil.isNotNull(arguments.getMethodKey())) {
            sb.append("MethodKey:[" + arguments.getMethodKey() + "]");
        }
        if (StrUtil.isNotNull(arguments.getInfoId())) {
            sb.append("InfoId:[" + arguments.getInfoId() + "]");
        }
        log.debug(sb.toString());
    }

    public Object invoke(MethodInvocation invocation) throws Throwable {
        String methodName = invocation.getMethod().getName();
        before2(methodName, invocation.getArguments(),
                invocation.getThis().getClass().getSimpleName());
        return invocation.proceed();
    }

    public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
            throws Throwable {
        log.debug(method.getName() + "方法调用后时间" + DateUtils
                .longToStr(System.currentTimeMillis(), FmtStr.hhmmssSSS));
    }

    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
        log.debug("方法调用前时间" + DateUtils.longToStr(System.currentTimeMillis(), FmtStr.hhmmssSSS));
        before2(arg0.getName(), arg1, arg2.getClass().getSimpleName());
    }

}
